package com.zwq.wxpay.sdk;

import java.io.*;

public class CommonWXPayConfig extends WXPayConfig {

    private PayBaseInformaion payBaseInformaion;

    public CommonWXPayConfig(PayBaseInformaion payBaseInformaion) {
        this.payBaseInformaion = payBaseInformaion;
    }

    @Override
    protected String getAppID() {
        return this.payBaseInformaion.getAppid();
    }

    @Override
    protected String getMchID() {
        return this.payBaseInformaion.getMchid();
    }

    @Override
    protected String getKey() {
        return this.payBaseInformaion.getKey();
    }

    @Override
    protected InputStream getCertStream() {
        ByteArrayInputStream certBis = null;

        String certName = this.payBaseInformaion.getCertPath();
        if (certName.equals("") || certName.length()<=0 || certName == null) {
            return new InputStream() {
                @Override
                public int read() throws IOException {
                    return 0;
                }
            };
        }

        String certPath = certName; //
        File file = new File(certPath);
        try {
            InputStream certStream = new FileInputStream(file);
            byte[] certData = new byte[(int) file.length()];
            certStream.read(certData);
            certStream.close();

            certBis = new ByteArrayInputStream(certData);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return certBis;
    }

    @Override
    public IWXPayDomain getWXPayDomain() {
        // 这个方法需要这样实现, 否则无法正常初始化WXPay
        IWXPayDomain iwxPayDomain = new IWXPayDomain() {
            public void report(String domain, long elapsedTimeMillis, Exception ex) {
            }
            public DomainInfo getDomain(WXPayConfig config) {
                return new IWXPayDomain.DomainInfo(WXPayConstants.DOMAIN_API, true);
            }
        };
        return iwxPayDomain;
    }
}
